//
//  LinkerChatViewController.m
//  Linker
//
//  Created by hhsoft on 16/4/23.
//  Copyright © 2016年 www.huahansoft.com. All rights reserved.
//

#import "LinkerChatViewController.h"
#import "EaseEmoji.h"
#import "EaseEmotionManager.h"
//#import "ChatGroupDetailViewController.h"
//#import "ChatroomDetailViewController.h"
#import "SVProgressHUDView.h"
//#import "SystemEngine.h"
//#import "UserProfileManager.h"
//-----------------------------------------------------------------------
//#import "ContactListSelectViewController.h"
//#import "ChatDemoHelper.h"
//#import "ChatSettingViewController.h"
#import "UserInfo.h"
//#import "DataBaseEngine.h"
//#import "UserInfoEngine.h"
//#import "UserInfoViewController.h"
//#import "HHSoftAppInfo.h"
//#import "AddFriendVerifyViewController.h"
//#import "FriendSystemEngine.h"
//#import "UserBriefInfoViewController.h"
#import "GlobalFile.h"
//#import "FriendsListViewController.h"
//#import "MessageTransferViewController.h"
//#import "LanguageSwitcherNetWork.h"

@interface LinkerChatViewController ()<UIAlertViewDelegate, EaseMessageViewControllerDelegate, EaseMessageViewControllerDataSource,LinkExportClientDelegate>
{
    UIMenuItem *_copyMenuItem;
    UIMenuItem *_deleteMenuItem;
    UIMenuItem *_transpondMenuItem;
    UIMenuItem *_revokeMenuItem;
    
        //子控制个数，用来判断是pop 还是push
    NSInteger _navControllerSubControllers;
}
@property(nonatomic) BOOL isPlayingAudio;
/*
 *  聊天好友信息 （单聊）
 */
@property(nonatomic,strong) UserInfo *friendInfo;
@property(nonatomic) NSMutableDictionary *emotionDic;

@property(nonatomic,assign) NSInteger jumpToIndex;
    //单聊顶部view
@property(nonatomic,strong) UIView *chatTopView;

@end

@implementation LinkerChatViewController
-(instancetype)initWithConversationChatter:(NSString *)conversationChatter conversationType:(LKConversationType)conversationType{
    self=[self initWithConversationChatter:conversationChatter conversationType:conversationType jumpToSearchedMessageIndex:-1];
    return self;
}
-(instancetype)initWithConversationChatter:(NSString *)conversationChatter conversationType:(LKConversationType)conversationType jumpToSearchedMessageIndex:(NSInteger)index{
    self=[super initWithConversationChatter:conversationChatter conversationType:conversationType];
    if (self) {
        _jumpToIndex=index;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.showRefreshHeader = YES;
    self.delegate = self;
    self.dataSource = self;
    self.tableView.backgroundColor=[GlobalFile themeColor];
    UIImage *senderImage=[UIImage imageNamed:@"chat_sender_bg.png"];
    UIImage *recevieImage=[UIImage imageNamed:@"chat_receiver_bg.png"];
    [[EaseBaseMessageCell appearance] setSendBubbleBackgroundImage:[senderImage stretchableImageWithLeftCapWidth:senderImage.size.width/2 topCapHeight:senderImage.size.height/2+5]];
    [[EaseBaseMessageCell appearance] setRecvBubbleBackgroundImage:[recevieImage stretchableImageWithLeftCapWidth:recevieImage.size.width/2 topCapHeight:recevieImage.size.height/2+5]];
    
    [[EaseBaseMessageCell appearance] setSendMessageVoiceAnimationImages:@[[UIImage imageNamed:@"chat_sender_audio_playing_full"], [UIImage imageNamed:@"chat_sender_audio_playing_000"], [UIImage imageNamed:@"chat_sender_audio_playing_001"], [UIImage imageNamed:@"chat_sender_audio_playing_002"], [UIImage imageNamed:@"chat_sender_audio_playing_003"]]];
    [[EaseBaseMessageCell appearance] setRecvMessageVoiceAnimationImages:@[[UIImage imageNamed:@"chat_receiver_audio_playing_full"],[UIImage imageNamed:@"chat_receiver_audio_playing000"], [UIImage imageNamed:@"chat_receiver_audio_playing001"], [UIImage imageNamed:@"chat_receiver_audio_playing002"], [UIImage imageNamed:@"chat_receiver_audio_playing003"]]];
    
    [[EaseBaseMessageCell appearance] setAvatarSize:40.f];
    [[EaseBaseMessageCell appearance] setAvatarCornerRadius:5.f];
    [[EaseBaseMessageCell appearance] setMessageNameHeight:10];
    
    [[EaseChatBarMoreView appearance] setMoreViewBackgroundColor:[UIColor colorWithRed:240 / 255.0 green:242 / 255.0 blue:247 / 255.0 alpha:1.0]];
    
    [self _setupBarButtonItem];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deleteAllMessages:) name:KNOTIFICATIONNAME_DELETEALLMESSAGE object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(exitGroup) name:@"ExitGroup" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(insertCallMessage:) name:@"insertCallMessage" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(revokeMessage:) name:@"RevokeMessage_Notication" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleCallNotification:) name:@"callOutWithChatter" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleCallNotification:) name:@"callControllerClose" object:nil];
    
        //移除全部消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(chatterAllMeesageRemoved:) name:@"Notification_ChatterAllMeesageRemoved" object:nil];
        //屏蔽状态更改
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(chatterMaskingStatusChanged:) name:@"Notification_ChatterMaskingStatusChanged" object:nil];
        //好友关系更改
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(chatterRelationTypeChanged:) name:@"Notification_ChatterRelationTypeChanged" object:nil];
    
    if (_jumpToIndex==-1) {
            //通过会话管理者获取已收发消息
        [self tableViewDidTriggerHeaderRefresh];
    }else{
        self.navigationItem.rightBarButtonItem=nil;
        if (_jumpToIndex<self.messageCountOfPage) {
            _jumpToIndex=self.messageCountOfPage;
        }
            //跳到搜索历史界面
        [self jumpToHistoryMessageIndex:_jumpToIndex totalCount:_jumpToIndex];
    }

    if (self.conversation.type==LKConversationTypeChat) {
//        UserInfo *myInfo=[UserInfoEngine getLoginUser];
        UserInfo *myInfo = [[UserInfo alloc] init];
        NSDictionary *userInfoDic=[NSDictionary dictionaryWithObjectsAndKeys:[@(myInfo.userID) stringValue],@"friend_id",
                                   myInfo.userNickName,@"friend_nickname",
                                   myInfo.userAvatar,@"friend_avatar",
                                   myInfo.nickNameFristLetter,@"first_letter",
                                   [@(myInfo.userIsTeacher) stringValue],@"is_teacher", nil];
            //发送透传消息
        [self sendCmdMessageWithAction:@"USER_INFO" ext:userInfoDic];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    if (self.conversation.type == LKConversationTypeChatRoom)
    {
        //退出聊天室，删除会话
//        NSString *chatter = [self.conversation.conversationId copy];
//        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//            EMError *error = nil;
//            [[EMClient sharedClient].roomManager leaveChatroom:chatter error:&error];
//            if (error !=nil) {
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error" message:[NSString stringWithFormat:@"Leave chatroom '%@' failed [%@]", chatter, error.errorDescription] delegate:nil cancelButtonTitle:LinkerLocalizedString(@"alert_OK", nil) otherButtonTitles:nil, nil];
//                    [alertView show];
//                });
//            }
//        });
    }
//
//    [[EMClient sharedClient] removeDelegate:self];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    self.navigationController.interactivePopGestureRecognizer.delaysTouchesBegan=NO;
    
    _navControllerSubControllers=self.navigationController.viewControllers.count;
    if (self.conversation.type == LKConversationTypeGroupChat) {
        if ([[self.conversation.ext objectForKey:@"subject"] length])
        {
            self.title = [self.conversation.ext objectForKey:@"subject"];
        }
    }
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    self.navigationController.interactivePopGestureRecognizer.delaysTouchesBegan=YES;
    
    if (self.navigationController.viewControllers.count==_navControllerSubControllers+1) {
            //push
    }else if(self.navigationController.viewControllers.count==_navControllerSubControllers-1) {
            //pop
        [[LinkExportClient sharedClient].chatManager removeDelegate];
//        [[EMClient sharedClient].roomManager removeDelegate:self];
            //[[ChatDemoHelper shareHelper] setChatVC:nil];
        
        if (self.deleteConversationIfNull) {
                //判断当前会话是否为空，若符合则删除该会话
            LKMessage *message = [self.conversation latestMessage];
            if (message == nil) {
                [[LinkExportClient sharedClient].chatManager deleteConversation:self.conversation.conversationId isDeleteMessages:NO completion:^(NSString *aConversationId, LKError *aError) {
                    
                }];
            }
        }
    }
}

-(void)setChatFirend:(UserInfo *)friendInfo isSave:(BOOL)isSave{
    _friendInfo=friendInfo;
        //保存聊天对象信息
//    if (_friendInfo && isSave) {
//        [[DataBaseEngine sharedDBEngine] addFriend:_friendInfo];
//    }
//    if (_friendInfo.userRelationType==3) {
//        [self setStrangerTopView];
//    }
//    if (_friendInfo) {
//        UserInfo *myInfo=[UserInfoEngine getLoginUser];
//            //必须都是学生且好友 才能语音视频
//        if ((_friendInfo.userRelationType==1 || _friendInfo.userRelationType==2) && _friendInfo.userIsTeacher==NO && myInfo.userIsTeacher==NO) {
//        }else{
//            [self setIsHiddenVideoAndVicieActionButton:YES];
//        }
//    }
}
#pragma mark - setup subviews

- (void)_setupBarButtonItem
{
    /*
    UIBarButtonItem *backBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back.png"] style:UIBarButtonItemStylePlain target:self action:@selector(backAction)];
    [backBarButtonItem setTitle:@"返回"];
    [self.navigationItem setLeftBarButtonItem:backBarButtonItem];
     */
    //单聊
    if (self.conversation.type == LKConversationTypeChat) {
        UIBarButtonItem *infoBarButtonItem=[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"tabbar_usercenter_uncheck.png"] style:UIBarButtonItemStylePlain target:self action:@selector(userInfoBarClick)];
        self.navigationItem.rightBarButtonItem = infoBarButtonItem;
    }
    else{//群聊
        UIButton *detailButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 44)];
        [detailButton setImage:[UIImage imageNamed:@"home_group_classroom.png"] forState:UIControlStateNormal];
        [detailButton addTarget:self action:@selector(showGroupDetailAction) forControlEvents:UIControlEventTouchUpInside];
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:detailButton];
    }
}
-(void)setStrangerTopView{
    if (_friendInfo.userRelationType==1||_friendInfo.userRelationType==2) {
        if (_chatTopView) {
            [_chatTopView removeFromSuperview];
            CGRect frame = self.tableView.frame;
            frame.origin.y-=40;
            frame.size.height+=40;
            self.tableView.frame=frame;
        }
    }else if (_friendInfo.userRelationType==3){
        if (nil==_chatTopView) {
            _chatTopView=[[UIView alloc] initWithFrame:CGRectMake(0, 0,ScreenWidth, 40)];
                //屏蔽
            UIButton *shieldButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth/2, 40)];
                //[shieldButton setImage:[UIImage imageNamed:@"delete"] forState:UIControlStateNormal];
//            BOOL isMaskingUser=[[DataBaseEngine sharedDBEngine] isMaskingUserWithUserID:_friendInfo.userID];
//            if (isMaskingUser) {
//                [shieldButton setTitle:LinkerLocalizedString(@"chat_removeMaskingButtonTitle", nil) forState:UIControlStateNormal];
//            }else{
//                [shieldButton setTitle:LinkerLocalizedString(@"chat_MaskingTheOneButtonTitle", nil) forState:UIControlStateNormal];
//            }
            shieldButton.tag=345;
            shieldButton.titleLabel.font=[UIFont systemFontOfSize:14];
            [shieldButton setTitleColor:[UIColor colorWithRed:51.0/255.0f green:51.0/255.0f blue:51.0/255.0f alpha:1] forState:UIControlStateNormal];
            [shieldButton addTarget:self action:@selector(shieldButtonClick:) forControlEvents:UIControlEventTouchUpInside];
                //加为好友
            UIButton *addFriendButton = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth/2, 0, ScreenWidth/2, 40)];
            addFriendButton.titleLabel.font=[UIFont systemFontOfSize:14];
                //[addFriendButton setImage:[UIImage imageNamed:@"delete"] forState:UIControlStateNormal];
            [addFriendButton setTitle:@"添加好友" forState:UIControlStateNormal];
            [addFriendButton setTitleColor:[UIColor colorWithRed:51.0/255.0f green:51.0/255.0f blue:51.0/255.0f alpha:1] forState:UIControlStateNormal];
            [addFriendButton addTarget:self action:@selector(addFriendButtonClick:) forControlEvents:UIControlEventTouchUpInside];
            
            [self.view addSubview:_chatTopView];
            [_chatTopView addSubview:shieldButton];
            [_chatTopView addSubview:addFriendButton];
        }
        CGRect frame = self.tableView.frame;
        frame.origin.y+=40;
        frame.size.height-=40;
        self.tableView.frame=frame;
    }
}
#pragma mark - button click
-(void)shieldButtonClick:(UIButton *)sender{
    [SVProgressHUDView showWithStatus:@"链接超时！"];
//    BOOL isMaskingUser=[[DataBaseEngine sharedDBEngine] isMaskingUserWithUserID:_friendInfo.userID];
//    if (isMaskingUser) {
//            //已屏蔽，取消屏蔽
//        [[[FriendSystemEngine alloc] init] removeMaskingUserWithFriendID:[@(_friendInfo.userID) stringValue] removeSuccessed:^(NSInteger code) {
//            [SVProgressHUDView dismiss];
//            if (code==0) {
//                [sender setTitle:LinkerLocalizedString(@"chat_MaskingTheOneButtonTitle", nil) forState:UIControlStateNormal];
//                [[DataBaseEngine sharedDBEngine] removeMaskingUserWithUserID:_friendInfo.userID];
//                [SVProgressHUDView showSuccessWithStatus:[SystemEngine setTitleInfoWithLanguageInfo:NSLocalizedString(@"alert_chatSetting_removedMasking", nil)]];
//            }else{
//                [SVProgressHUDView showErrorWithStatus:[SystemEngine setTitleInfoWithLanguageInfo:NSLocalizedString(@"alert_chatSetting_removeMaskingFail", nil)]];
//            }
//        } error:^(NSInteger code, NSString *responseMessage) {
//            [SVProgressHUDView showErrorWithStatus:[SystemEngine setTitleInfoWithLanguageInfo:NSLocalizedString(@"alert_chatSetting_removeMaskingFail", nil)]];
//        }];
//    }else{
//            //屏蔽
//        [[[FriendSystemEngine alloc] init] maskingUserWithFriendID:[@(_friendInfo.userID) stringValue] nickName:_friendInfo.userNickName avatar:_friendInfo.userAvatar maskingSuccessed:^(NSInteger code) {
//            [SVProgressHUDView dismiss];
//            if (code==0) {
//                [sender setTitle:LinkerLocalizedString(@"chat_removeMaskingButtonTitle", nil) forState:UIControlStateNormal];
//                [[DataBaseEngine sharedDBEngine] addMaskingUser:_friendInfo];
//                [SVProgressHUDView showSuccessWithStatus:[SystemEngine setTitleInfoWithLanguageInfo:NSLocalizedString(@"alert_chatSetting_MaskingTheOne", nil)]];
//            }else{
//                [SVProgressHUDView showErrorWithStatus:[SystemEngine setTitleInfoWithLanguageInfo:NSLocalizedString(@"alert_chatSetting_MaskingFail", nil)]];
//            }
//        } error:^(NSInteger code, NSString *responseMessage) {
//            [SVProgressHUDView showErrorWithStatus:[SystemEngine setTitleInfoWithLanguageInfo:NSLocalizedString(@"alert_chatSetting_MaskingFail", nil)]];
//        }];
//    }
}
//同意好友申请
-(void)agreeApplyOrAddFriend:(BOOL )isAggree{
    [SVProgressHUDView showWithStatus:@"正在等待。。。"];
//    UserInfo *user=[UserInfoEngine getLoginUser];
    UserInfo *user = [[UserInfo alloc] init];
//    [[[FriendSystemEngine alloc] init] addFriendWithFriendID:[@(_friendInfo.userID) stringValue] friendNickName:_friendInfo.userNickName friendAvatar:_friendInfo.userAvatar userID:user.userID userNickName:user.userNickName userAvatar:user.userAvatar addSuccessed:^(NSInteger code, UserInfo *friendInfo) {
//        [SVProgressHUDView dismiss];
//        if (code==0) {
//            [SVProgressHUDView showSuccessWithStatus:LinkerLocalizedString(@"alert_chatSetting_addFirendSuccess", nil)];
//
//            if (isAggree) {
//                [[ChatDemoHelper shareHelper] sendAgreeApplyCmdMessageWithUsername:[@(_friendInfo.userID) stringValue]];
//            }else{
//                [[ChatDemoHelper shareHelper].contactViewVC reloadDataSource];
//            }
//            _friendInfo.userRelationType=1;
//            [self setStrangerTopView];
//        }else{
//            [SVProgressHUDView showErrorWithStatus:LinkerLocalizedString(@"alert_chatSetting_addFirendFail", nil)];
//        }
//    } error:^(NSInteger code, NSString *responseMessage) {
//        [SVProgressHUDView dismiss];
//        [SVProgressHUDView showErrorWithStatus:LinkerLocalizedString(@"alert_chatSetting_addFirendFail", nil)];
//    }];
}
-(void)addFriendButtonClick:(id)sender{
//    if (_friendInfo.userReverseRelationType==1) {
//            //直接添加好友
//        [self agreeApplyOrAddFriend:NO];
//    }else{
//        AddFriendVerifyViewController *verifyController=[[AddFriendVerifyViewController alloc] initWithUserInfo:_friendInfo];
//        verifyController.hidesBottomBarWhenPushed=YES;
//        [self.navigationController pushViewController:verifyController animated:YES];
//    }
}
-(void)userInfoBarClick{
    /*
    UserBriefInfoViewController *userBriefController=[[UserBriefInfoViewController alloc] initWithFriendID:[self.conversation.conversationId integerValue] controllerType:UserBriefInfoControllerTypeChat];
    userBriefController.hidesBottomBarWhenPushed=YES;
    [self.navigationController pushViewController:userBriefController animated:YES];
     */

//    ChatSettingViewController *settingController=[[ChatSettingViewController alloc] initWithFriendInfo:_friendInfo];
//    [self.navigationController pushViewController:settingController animated:YES];
}
#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.cancelButtonIndex != buttonIndex) {
        self.messageTimeIntervalTag = -1;
        [self.conversation deleteAllMessages:nil];
        [self.dataArray removeAllObjects];
        [self.messsagesSource removeAllObjects];
        
        [self.tableView reloadData];
    }
}

#pragma mark - EaseMessageViewControllerDelegate
- (NSString *)messageViewController:(EaseMessageViewController *)viewController stringForDate:(NSDate *)date{
    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    NSString *lang=@"en";
    [dateFormatter setLocale:[NSLocale localeWithLocaleIdentifier:lang]];
    if ([lang isEqualToString:@"en"]) {
        [dateFormatter setDateFormat:@"MM/dd/yyyy hh:mm:ss aaa"];
    }else{
        [dateFormatter setDateFormat:@"yyyy/MM/dd HH:mm:ss"];
    }
    NSString *timeStr=[dateFormatter stringFromDate:date];
    return timeStr;
}
- (BOOL)messageViewController:(EaseMessageViewController *)viewController
   canLongPressRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (BOOL)messageViewController:(EaseMessageViewController *)viewController
   didLongPressRowAtIndexPath:(NSIndexPath *)indexPath
{
    id object = [self.dataArray objectAtIndex:indexPath.row];
    if (![object isKindOfClass:[NSString class]]) {
        if (![object isDisplayMessage]) {
            EaseMessageCell *cell = (EaseMessageCell *)[self.tableView cellForRowAtIndexPath:indexPath];
            [cell becomeFirstResponder];
            self.menuIndexPath = indexPath;
            [self _showMenuViewController:cell.bubbleView andIndexPath:indexPath messageType:cell.model.bodyType messageExt:cell.model.message.ext timeInvite:cell.model.message.timestamp isSender:cell.model.isSender];
        }
    }
    return YES;
}

- (void)messageViewController:(EaseMessageViewController *)viewController
  didSelectAvatarMessageModel:(id<IMessageModel>)messageModel
{
//    if (messageModel.isSender) {
//        UserInfoViewController *userInfoViewController = [[UserInfoViewController alloc] init];
//        userInfoViewController.isTeacher = [UserInfoEngine getLoginUser].userIsTeacher;
//        userInfoViewController.hidesBottomBarWhenPushed = YES;
//        [self.navigationController pushViewController:userInfoViewController animated:YES];
//    }else{
//        UserBriefInfoViewController *userBriefController=[[UserBriefInfoViewController alloc] initWithFriendID:[messageModel.message.from integerValue] controllerType:UserBriefInfoControllerTypeChat];
//        userBriefController.hidesBottomBarWhenPushed=YES;
//        [self.navigationController pushViewController:userBriefController animated:YES];
//    }
}

#pragma mark - EaseMessageViewControllerDataSource

- (id<IMessageModel>)messageViewController:(EaseMessageViewController *)viewController
                           modelForMessage:(LKMessage *)message
{
    id<IMessageModel> model = nil;
    model = [[EaseMessageModel alloc] initWithMessage:message];
    
    if (message.direction==LKMessageDirectionSend) {
//        UserInfo *currentUser=[UserInfoEngine getLoginUser];
//        model.avatarURLPath=currentUser.userAvatar;
//        model.nickname=currentUser.userDisplayName;
    }else{
//        UserInfo *userInfo=[[DataBaseEngine sharedDBEngine] getFriendInfoWithFriendID:message.from];
//        if (userInfo) {
//            model.avatarURLPath=userInfo.userAvatar;
//            model.nickname=userInfo.userDisplayName;
//        }else{
//            model.avatarImage = [GlobalFile HHSoftDefaultImg];
//        }
    }
    
    /*
    model.avatarImage = [UIImage imageNamed:@"EaseUIResource.bundle/user"];
    UserProfileEntity *profileEntity = [[UserProfileManager sharedInstance] getUserProfileByUsername:model.nickname];
    if (profileEntity) {
        model.avatarURLPath = profileEntity.imageUrl;
        model.nickname = profileEntity.nickname;
    }
     */
    model.failImageName = @"imageDownloadFail";
    return model;
}
-(BOOL)messageViewController:(EaseMessageViewController *)viewController didSelectMessageModel:(id<IMessageModel>)messageModel{
//    if (messageModel.bodyType==LKMessageBodyTypeText) {
//        NSDictionary *ext=messageModel.message.ext;
//        if (ext && ([ext[@"callState"] integerValue]==9 || [ext[@"callState"] integerValue]==8)) {
//            UserInfo *friendInfo=[[DataBaseEngine sharedDBEngine] getFriendInfoWithFriendID:messageModel.message.direction==EMMessageDirectionReceive?messageModel.message.from:messageModel.message.to];
//            if (![UserInfoEngine getLoginUser].userIsTeacher && !friendInfo.userIsTeacher) {//重新拨打
//                NSInteger type=[ext[@"callType"] integerValue];
//                    // 隐藏键盘
//                [self.chatToolbar endEditing:YES];
//                [[NSNotificationCenter defaultCenter] postNotificationName:KNOTIFICATION_CALL object:@{@"chatter":self.conversation.conversationId, @"type":[NSNumber numberWithInteger:type]}];
//            }
//        }
//    }else{
//
//    }
    return NO;
}
- (NSArray*)emotionFormessageViewController:(EaseMessageViewController *)viewController
{
    NSMutableArray *emotions = [NSMutableArray array];
    for (NSString *name in [EaseEmoji allEmoji]) {
        EaseEmotion *emotion = [[EaseEmotion alloc] initWithName:@"" emotionId:name emotionThumbnail:name emotionOriginal:name emotionOriginalURL:@"" emotionType:EMEmotionDefault];
        [emotions addObject:emotion];
    }
    EaseEmotion *temp = [emotions objectAtIndex:0];
    EaseEmotionManager *managerDefault = [[EaseEmotionManager alloc] initWithType:EMEmotionDefault emotionRow:3 emotionCol:7 emotions:emotions tagImage:[UIImage imageNamed:temp.emotionId]];
    
    NSMutableArray *emotionGifs = [NSMutableArray array];
    _emotionDic = [NSMutableDictionary dictionary];
    NSArray *names = @[@"icon_002",@"icon_007",@"icon_010",@"icon_012",@"icon_013",@"icon_018",@"icon_019",@"icon_020",@"icon_021",@"icon_022",@"icon_024",@"icon_027",@"icon_029",@"icon_030",@"icon_035",@"icon_040"];
    int index = 0;
    for (NSString *name in names) {
        index++;
        EaseEmotion *emotion = [[EaseEmotion alloc] initWithName:[NSString stringWithFormat:@"[示例%d]",index] emotionId:[NSString stringWithFormat:@"em%d",(1000 + index)] emotionThumbnail:[NSString stringWithFormat:@"%@_cover",name] emotionOriginal:[NSString stringWithFormat:@"%@",name] emotionOriginalURL:@"" emotionType:EMEmotionGif];
        [emotionGifs addObject:emotion];
        [_emotionDic setObject:emotion forKey:[NSString stringWithFormat:@"em%d",(1000 + index)]];
    }
        // EaseEmotionManager *managerGif= [[EaseEmotionManager alloc] initWithType:EMEmotionGif emotionRow:2 emotionCol:4 emotions:emotionGifs tagImage:[UIImage imageNamed:@"icon_002_cover"]];
    
        //return @[managerDefault,managerGif];
    return @[managerDefault];
}

- (BOOL)isEmotionMessageFormessageViewController:(EaseMessageViewController *)viewController
                                    messageModel:(id<IMessageModel>)messageModel
{
    BOOL flag = NO;
    if ([messageModel.message.ext objectForKey:MESSAGE_ATTR_IS_BIG_EXPRESSION]) {
        return YES;
    }
    return flag;
}

- (EaseEmotion*)emotionURLFormessageViewController:(EaseMessageViewController *)viewController
                                      messageModel:(id<IMessageModel>)messageModel
{
    NSString *emotionId = [messageModel.message.ext objectForKey:MESSAGE_ATTR_EXPRESSION_ID];
    EaseEmotion *emotion = [_emotionDic objectForKey:emotionId];
    if (emotion == nil) {
        emotion = [[EaseEmotion alloc] initWithName:@"" emotionId:emotionId emotionThumbnail:@"" emotionOriginal:@"" emotionOriginalURL:@"" emotionType:EMEmotionGif];
    }
    return emotion;
}

- (NSDictionary*)emotionExtFormessageViewController:(EaseMessageViewController *)viewController
                                        easeEmotion:(EaseEmotion*)easeEmotion
{
    return @{MESSAGE_ATTR_EXPRESSION_ID:easeEmotion.emotionId,MESSAGE_ATTR_IS_BIG_EXPRESSION:@(YES)};
}

#pragma mark - EaseMob

#pragma mark - EMClientDelegate

- (void)didLoginFromOtherDevice
{
    if ([self.imagePicker.mediaTypes count] > 0 && [[self.imagePicker.mediaTypes objectAtIndex:0] isEqualToString:(NSString *)kUTTypeMovie]) {
        [self.imagePicker stopVideoCapture];
    }
}

- (void)didRemovedFromServer
{
    if ([self.imagePicker.mediaTypes count] > 0 && [[self.imagePicker.mediaTypes objectAtIndex:0] isEqualToString:(NSString *)kUTTypeMovie]) {
        [self.imagePicker stopVideoCapture];
    }
}

#pragma mark - action

- (void)backAction
{
//    [[LinkExportClient sharedClient].chatManager removeDelegate];
//    [[LinkExportClient sharedClient].roomManager removedele];
        //[[ChatDemoHelper shareHelper] setChatVC:nil];
    
    if (self.deleteConversationIfNull) {
        //判断当前会话是否为空，若符合则删除该会话
        LKMessage *message = [self.conversation latestMessage];
        if (message == nil) {
            [[LinkExportClient sharedClient].chatManager deleteConversation:self.conversation.conversationId isDeleteMessages:NO completion:^(NSString *aConversationId, LKError *aError) {
                
            }];
        }
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)showGroupDetailAction
{
    [self.view endEditing:YES];
//    if (self.conversation.type == LKConversationTypeGroupChat) {
//        ChatGroupDetailViewController *detailController = [[ChatGroupDetailViewController alloc] initWithGroupId:self.conversation.conversationId];
//        [self.navigationController pushViewController:detailController animated:YES];
//    }
//    else if (self.conversation.type == EMConversationTypeChatRoom)
//    {
//        ChatroomDetailViewController *detailController = [[ChatroomDetailViewController alloc] initWithChatroomId:self.conversation.conversationId];
//        [self.navigationController pushViewController:detailController animated:YES];
//    }
}

- (void)deleteAllMessages:(id)sender
{
    if (self.dataArray.count == 0) {
        [self showHint:NSLocalizedString(@"message.noMessage", @"no messages")];
        return;
    }
    
    if ([sender isKindOfClass:[NSNotification class]]) {
        NSString *groupId = (NSString *)[(NSNotification *)sender object];
        BOOL isDelete = [groupId isEqualToString:self.conversation.conversationId];
        if (self.conversation.type != LKConversationTypeChat && isDelete) {
            self.messageTimeIntervalTag = -1;
            [self.conversation deleteAllMessages:nil];
            [self.messsagesSource removeAllObjects];
            [self.dataArray removeAllObjects];
            
            [self.tableView reloadData];
            [self showHint:@"暂无消息"];
        }
    }
    else if ([sender isKindOfClass:[UIButton class]]){
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"please make sure to delete" message:nil delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"OK", nil];
        [alertView show];
    }
}

- (void)transpondMenuAction:(id)sender
{
    if (self.menuIndexPath && self.menuIndexPath.row > 0) {
        id<IMessageModel> model = [self.dataArray objectAtIndex:self.menuIndexPath.row];
        
        /*
        FriendsListViewController *friendsListController=[[FriendsListViewController alloc] initWithMessage:model.message];
        friendsListController.hidesBottomBarWhenPushed=YES;
        [self.navigationController pushViewController:friendsListController animated:YES];
         */
//        MessageTransferViewController *transferController=[[MessageTransferViewController alloc] initWithMessage:model.message];
//        transferController.hidesBottomBarWhenPushed=YES;
//        [self.navigationController pushViewController:transferController animated:YES];
    }
    self.menuIndexPath = nil;
}
//撤回消息
-(void)revokeMenuAction:(id)sneder{
    if (self.menuIndexPath && self.menuIndexPath.row > 0) {
        id<IMessageModel> model = [self.dataArray objectAtIndex:self.menuIndexPath.row];
            //发送撤回消息
//        [self sendCmdMessageWithAction:@"REVOKE_FLAG" ext:@{@"msgId":model.message.messageId}];
//
//        NSString *text=[NSString stringWithFormat:@"%@",LinkerLocalizedString(@"ringletter_youreovkeamessage", nil)];
//        EMTextMessageBody *body=[[EMTextMessageBody alloc] initWithText:text];
//        EMMessage *revokeMessage=[[EMMessage alloc] initWithConversationID:self.conversation.conversationId from:model.message.from to:model.message.to body:body ext:@{@"isRevoke":@(YES)}];
//        revokeMessage.chatType=model.message.chatType;
//        revokeMessage.direction=EMMessageDirectionSend;
//
//        [self.conversation deleteMessageWithId:model.message.messageId error:nil];
//        [[EMClient sharedClient].chatManager importMessages:@[revokeMessage] completion:^(EMError *aError) {
//
//        }];
//        id<IMessageModel> message=[self messageViewController:self modelForMessage:revokeMessage];
//        [self.dataArray replaceObjectAtIndex:self.menuIndexPath.row withObject:message];
//        [self.tableView reloadRowsAtIndexPaths:@[self.menuIndexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
    self.menuIndexPath = nil;
}
- (void)copyMenuAction:(id)sender
{
    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
    if (self.menuIndexPath && self.menuIndexPath.row > 0) {
        id<IMessageModel> model = [self.dataArray objectAtIndex:self.menuIndexPath.row];
        pasteboard.string = model.text;
    }
    
    self.menuIndexPath = nil;
}

- (void)deleteMenuAction:(id)sender
{
    if (self.menuIndexPath && self.menuIndexPath.row > 0) {
        id<IMessageModel> model = [self.dataArray objectAtIndex:self.menuIndexPath.row];
        NSMutableIndexSet *indexs = [NSMutableIndexSet indexSetWithIndex:self.menuIndexPath.row];
        NSMutableArray *indexPaths = [NSMutableArray arrayWithObjects:self.menuIndexPath, nil];
        
        [self.conversation deleteMessageWithId:model.message.messageId];
        [self.messsagesSource removeObject:model.message];
        
        if (self.menuIndexPath.row - 1 >= 0) {
            id nextMessage = nil;
            id prevMessage = [self.dataArray objectAtIndex:(self.menuIndexPath.row - 1)];
            if (self.menuIndexPath.row + 1 < [self.dataArray count]) {
                nextMessage = [self.dataArray objectAtIndex:(self.menuIndexPath.row + 1)];
            }
            if ((!nextMessage || [nextMessage isKindOfClass:[NSString class]]) && [prevMessage isKindOfClass:[NSString class]]) {
                [indexs addIndex:self.menuIndexPath.row - 1];
                [indexPaths addObject:[NSIndexPath indexPathForRow:(self.menuIndexPath.row - 1) inSection:0]];
            }
        }
        
        [self.dataArray removeObjectsAtIndexes:indexs];
        [self.tableView beginUpdates];
        [self.tableView deleteRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationFade];
        [self.tableView endUpdates];
        
        if ([self.dataArray count] == 0) {
            self.messageTimeIntervalTag = -1;
        }
    }
    
    self.menuIndexPath = nil;
}

#pragma mark - notification
- (void)exitGroup
{
    [self.navigationController popToViewController:self animated:NO];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)insertCallMessage:(NSNotification *)notification
{
    id object = notification.object;
    if (object) {
        LKMessage *message = (LKMessage *)object;
        [self addMessageToDataSource:message progress:nil];
        [[LinkExportClient sharedClient].chatManager importMessages:@[message] completion:^(LKError *aError) {
            
        }];
    }
}
- (void)revokeMessage:(NSNotification *)notification{
    id object = notification.object;
    if (object) {
        LKMessage *revokeMessage=object[@"revokeMessage"];
        LKMessage *delelteMessage=object[@"deleteMessage"];
        NSString *messageID=delelteMessage.ext[@"msgId"];
        [self.dataArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if (![obj isKindOfClass:[NSString class]]) {
                id<IMessageModel> model = obj;
                if ([model.messageId isEqualToString:messageID]) {
                    id<IMessageModel> message=[self messageViewController:self modelForMessage:revokeMessage];
                    [self.conversation deleteMessageWithId:model.message.messageId];
                    [self.dataArray replaceObjectAtIndex:idx withObject:message];
                    NSIndexPath *indexPath=[NSIndexPath indexPathForRow:idx inSection:0];
                    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
                    *stop=YES;
                }
            }
        }];
    }
}
- (void)handleCallNotification:(NSNotification *)notification
{
    id object = notification.object;
    if ([object isKindOfClass:[NSDictionary class]]) {
        //开始call
        self.isViewDidAppear = NO;
    } else {
        //结束call
        self.isViewDidAppear = YES;
    }
}
-(void)chatterAllMeesageRemoved:(NSNotification *)notification{
    [self.dataArray removeAllObjects];
    [self.tableView reloadData];
}
-(void)chatterMaskingStatusChanged:(NSNotification *)notification{
    id object = notification.object;
    BOOL isMasking=[object boolValue];
    UIButton *shieldButton=(UIButton *)[self.view viewWithTag:345];
//    if (isMasking) {
//        [shieldButton setTitle:LinkerLocalizedString(@"chat_removeMaskingButtonTitle", nil) forState:UIControlStateNormal];
//    }else{
//        [shieldButton setTitle:LinkerLocalizedString(@"chat_MaskingTheOneButtonTitle", nil) forState:UIControlStateNormal];
//    }
}
-(void)chatterRelationTypeChanged:(NSNotification *)notification{
    id object = notification.object;
    NSInteger relationType=[object integerValue];
    _friendInfo.userRelationType=relationType;
    [self setStrangerTopView];
}

#pragma mark - private

- (void)_showMenuViewController:(UIView *)showInView
                   andIndexPath:(NSIndexPath *)indexPath
                    messageType:(LKMessageBodyType)messageType
                     messageExt:(NSDictionary *)ext
                     timeInvite:(NSTimeInterval)timeInvite
                       isSender:(BOOL)isSender
{
    if (self.menuController == nil) {
        self.menuController = [UIMenuController sharedMenuController];
    }
    
    if (_deleteMenuItem == nil) {
        _deleteMenuItem = [[UIMenuItem alloc] initWithTitle:@"Delete" action:@selector(deleteMenuAction:)];
    }
    
    if (_copyMenuItem == nil) {
        _copyMenuItem = [[UIMenuItem alloc] initWithTitle:@"Copy" action:@selector(copyMenuAction:)];
    }
    if (_transpondMenuItem == nil) {
        _transpondMenuItem = [[UIMenuItem alloc] initWithTitle:@"Transpond" action:@selector(transpondMenuAction:)];
    }
    if (_revokeMenuItem==nil) {
        _revokeMenuItem=[[UIMenuItem alloc] initWithTitle:@"Revoke" action:@selector(revokeMenuAction:)];
    }
    
    BOOL showRevokeItem=NO;
    if (isSender) {
        NSTimeInterval timeInterval =[[NSDate date] timeIntervalSince1970] - timeInvite/1000;
            //两分钟内 可撤销消息
        if (timeInterval<120) {
            showRevokeItem=YES;
        }
    }
    if (messageType == LKMessageBodyTypeText) {
        if (ext) {
            [self.menuController setMenuItems:@[_deleteMenuItem]];
        }else{
            if (showRevokeItem) {
                [self.menuController setMenuItems:@[_copyMenuItem, _deleteMenuItem,_revokeMenuItem,_transpondMenuItem]];
            }else{
                [self.menuController setMenuItems:@[_copyMenuItem, _deleteMenuItem,_transpondMenuItem]];
            }
        }
    } else if (messageType == LKMessageBodyTypeImage){
        if (showRevokeItem) {
            [self.menuController setMenuItems:@[_deleteMenuItem,_revokeMenuItem,_transpondMenuItem]];
        }else{
            [self.menuController setMenuItems:@[_deleteMenuItem,_transpondMenuItem]];
        }
    } else {
        if (showRevokeItem) {
            [self.menuController setMenuItems:@[_deleteMenuItem,_revokeMenuItem]];
        }else{
            [self.menuController setMenuItems:@[_deleteMenuItem]];
        }
    }
    [self.menuController setTargetRect:showInView.frame inView:showInView.superview];
    [self.menuController setMenuVisible:YES animated:YES];
}

@end
